<template>
	<view class="message-subscription-page">
		<!-- 自定义头部 -->
		<headerSlotVue :propsColor="'#ff6444'">
			<template v-slot:header>
				<view class="header-container" @click="closePage()">
					<view class="back-btn">
						<text class="cuIcon-back"></text>
					</view>
					<view class="page-title">
						消息订阅
					</view>
				</view>
			</template>
		</headerSlotVue>

		<!-- 主要内容区域 -->
		<view class="content-container">
			<!-- 提示信息卡片 -->
			<view class="tip-card">
				<view class="tip-header">
					<view class="tip-icon">
						<text class="cuIcon-notification"></text>
					</view>
					<text class="tip-title">温馨提示</text>
				</view>
				<view class="tip-list">
					<view class="tip-item" v-for="(tip, index) in tipList" :key="index">
						<text class="tip-number">{{index + 1}}</text>
						<text class="tip-text">{{tip}}</text>
					</view>
				</view>
			</view>

			<!-- 订阅列表 -->
			<view class="subscription-section">
				<view class="section-header">
					<view class="header-icon">
						<text class="cuIcon-settings"></text>
					</view>
					<text class="header-title">订阅设置</text>
				</view>

				<view class="subscription-list">
					<view class="subscription-item" v-for="item in subscribeList" :key="item.id">
						<view class="item-content">
							<view class="item-icon">
								<text :class="itemIconMap[item.key] || 'cuIcon-notification'"></text>
							</view>
							<view class="item-info">
								<text class="item-title">{{item.title}}</text>
								<text class="item-desc">{{item.desc}}</text>
							</view>
						</view>
						<view class="item-action">
							<button class="subscribe-btn" :class="{ subscribed: item.switchStatus }"
								@click="handleSubscription(item)">
								<text v-if="item.switchStatus" class="btn-text">已订阅</text>
								<text v-else class="btn-text">订阅</text>
							</button>
						</view>
					</view>
				</view>
			</view>

			<!-- 一键订阅所有 -->
			<!-- <view class="all-subscription-section">
				<button class="all-subscribe-btn" @click="subscribeAllMessages">
					<text class="btn-icon cuIcon-check"></text>
					<text class="btn-text">一键订阅所有消息</text>
				</button>
			</view> -->
		</view>
	</view>
</template>

<script>
	import headerSlotVue from '@/components/header-slot.vue';
	import WechatTemplateMessage from '@/utils/WechatTemplateMessage.js';
	import { 
		subscribeWithdrawMessages, 
		subscribeOrderBasicMessages,
		subscribeOrderStatusMessages,
		subscribeCommunityMessages, 
		subscribeSystemMessages,
		subscribeAllMessages,
		checkTemplateSubscriptionStatus,
		openSubscriptionSettings
	} from '@/utils/wechat-subscription.js';

	export default {
		components: {
			headerSlotVue,
		},
		data() {
			// 创建模板消息实例
			const templateMessage = new WechatTemplateMessage();
			
			return {
				templateMessage: templateMessage, // 模板消息实例
				tipList: [
					'为了您及时接收重要通知，请进行手动订阅操作。',
					'请选择"总是保存以上选择，不再询问"。',
					'如需取消订阅，收到通知后在服务通知的消息卡片上点击拒收。'
				],
				itemIconMap: {
					'提现消息订阅': 'cuIcon-moneybag',
					'订单消息订阅': 'cuIcon-form',
					'订单状态订阅': 'cuIcon-form',
					'社区消息订阅': 'cuIcon-group',
					'系统消息订阅': 'cuIcon-service'
				},
				subscribeList: [{
						id: 1,
						key: '提现消息订阅',
						title: '提现消息订阅',
						desc: '接收提现申请进度、成功、失败等通知',
						switchStatus: false,
						tmplIds: templateMessage.getTemplateIds(['withdrawResult', 'withdrawFailed', 'withdrawSuccess']),
						subscribeFunction: 'withdraw'
					},
					{
						id: 2,
						key: '订单消息订阅',
						title: '订单消息订阅',
						desc: '接收新订单、订单接单、支付成功等通知',
						switchStatus: false,
						tmplIds: templateMessage.getTemplateIds(['newOrder', 'orderAccepted', 'paymentSuccess']),
						subscribeFunction: 'orderBasic'
					},
					{
						id: 3,
						key: '订单状态订阅',
						title: '订单状态订阅',
						desc: '接收订单接单、送达、取消、完成等状态变更通知',
						switchStatus: false,
						tmplIds: templateMessage.getTemplateIds(['orderAccepted', 'product_order_delivered']),
						subscribeFunction: 'orderStatus'
					},
					{
						id: 4,
						key: '社区消息订阅',
						title: '社区消息订阅',
						desc: '接收违规警告、举报通知、审核结果等消息',
						switchStatus: false,
						tmplIds: templateMessage.getTemplateIds(['violationWarning', 'reportedNotification', 'auditResult']),
						subscribeFunction: 'community'
					},
					{
						id: 5,
						key: '系统消息订阅',
						title: '系统消息订阅',
						desc: '接收站内信、系统公告等重要通知',
						switchStatus: false,
						tmplIds: templateMessage.getTemplateIds(['internalMessage']),
						subscribeFunction: 'system'
					}
				]
			};
		},
		onLoad() {
			this.initSubscriptions();
		},
		methods: {
			// 处理订阅操作
			async handleSubscription(item) {
				try {
					console.log('开始订阅:', item.title);
					
					// 检查订阅状态
					const statusResult = await checkTemplateSubscriptionStatus(item.tmplIds);
					console.log('当前订阅状态:', statusResult);
					
					if (!statusResult.success) {
						uni.showToast({
							title: '检查订阅状态失败',
							icon: 'none'
						});
						return;
					}
					
					// 如果主开关关闭，引导用户开启
					if (!statusResult.mainSwitch) {
						this.showOpenSettingGuide();
						return;
					}
					
					// 根据订阅类型执行相应的订阅函数
					let result;
					switch (item.subscribeFunction) {
						case 'withdraw':
							result = await subscribeWithdrawMessages();
							break;
						case 'orderBasic':
							result = await subscribeOrderBasicMessages();
							break;
						case 'orderStatus':
							result = await subscribeOrderStatusMessages();
							break;
						case 'community':
							result = await subscribeCommunityMessages();
							break;
						case 'system':
							result = await subscribeSystemMessages();
							break;
						default:
							throw new Error('未知的订阅类型');
					}
					console.log('订阅结果:', result);
					
					if (result.success) {
						if (result.hasAccepted) {
							uni.showToast({
								title: '订阅成功',
								icon: 'success'
							});
							item.switchStatus = true;
						} else if (result.hasRejected) {
							uni.showToast({
								title: '您已拒绝订阅',
								icon: 'none'
							});
						} else if (result.hasBanned) {
							uni.showToast({
								title: '订阅消息功能被禁用',
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: result.message || '订阅失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('订阅失败:', error);
					uni.showToast({
						title: '订阅失败',
						icon: 'none'
					});
				}
			},

			// 一键订阅所有消息
			async subscribeAllMessages() {
				try {
					uni.showLoading({
						title: '订阅中...'
					});
					
					const result = await subscribeAllMessages();
					
					uni.hideLoading();
					
					if (result.success) {
						if (result.hasAccepted) {
							uni.showToast({
								title: result.message || '订阅成功',
								icon: 'success',
								duration: 3000
							});
							// 更新已订阅的项状态
							this.updateSubscriptionStatus(result.results);
						} else if (result.hasRejected) {
							uni.showToast({
								title: '您已拒绝订阅',
								icon: 'none'
							});
						} else if (result.hasBanned) {
							uni.showToast({
								title: '订阅消息功能被禁用',
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: result.message || '订阅失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('一键订阅失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '订阅失败',
						icon: 'none'
					});
				}
			},

			// 引导用户打开设置
			showOpenSettingGuide() {
				uni.showModal({
					title: '消息订阅未开启',
					content: '需要开启消息订阅才能接收重要通知',
					confirmText: '去开启',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							openSubscriptionSettings();
						}
					}
				});
			},

			// 初始化订阅状态
			async initSubscriptions() {
				try {
					console.log('初始化订阅状态...');
					
					// 检查每个订阅项的权限状态
					for (let item of this.subscribeList) {
						if (item.tmplIds && item.tmplIds.length > 0) {
							const statusResult = await checkTemplateSubscriptionStatus(item.tmplIds);
							console.log(`${item.title} 订阅状态:`, statusResult);
							
							if (statusResult.success && statusResult.mainSwitch) {
								// 检查是否所有模板都被接受
								const allAccepted = item.tmplIds.every(tmplId => 
									statusResult.itemSettings[tmplId] === 'accept'
								);
								item.switchStatus = allAccepted;
							} else {
								item.switchStatus = false;
							}
						}
					}
				} catch (error) {
					console.error('初始化订阅状态失败:', error);
				}
			},

			// 更新订阅状态
			updateSubscriptionStatus(results) {
				// 根据订阅结果更新对应项的状态
				this.subscribeList.forEach(item => {
					if (item.tmplIds && item.tmplIds.length > 0) {
						// 检查该项的所有模板是否都被接受
						const allAccepted = item.tmplIds.every(tmplId => 
							results[tmplId] === 'accept'
						);
						if (allAccepted) {
							item.switchStatus = true;
						}
					}
				});
			},

			closePage() {
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.message-subscription-page {
		min-height: 100vh;
		background: linear-gradient(to bottom, #ff6444 30%, #f5f7fa 30%);
	}

	.header-container {
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		width: 100%;
		height: 88rpx;

		.back-btn {
			margin-right: 20rpx;
			padding: 8rpx;

			.cuIcon-back {
				font-size: 36rpx;
				color: #FFFFFF;
			}
		}

		.page-title {
			font-weight: 600;
			font-size: 36rpx;
			color: #FFFFFF;
		}
	}

	.content-container {
		padding: 32rpx;
	}

	.tip-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

		.tip-header {
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;

			.tip-icon {
				width: 48rpx;
				height: 48rpx;
				background: linear-gradient(135deg, #ff6444 0%, #ff8e53 100%);
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-right: 16rpx;

				.cuIcon-notification {
					font-size: 24rpx;
					color: #FFFFFF;
				}
			}

			.tip-title {
				font-size: 32rpx;
				color: #2C2622;
				font-weight: 600;
			}
		}

		.tip-list {
			.tip-item {
				display: flex;
				align-items: flex-start;
				margin-bottom: 16rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.tip-number {
					width: 32rpx;
					height: 32rpx;
					background: #ff6444;
					color: #FFFFFF;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 20rpx;
					font-weight: 600;
					margin-right: 16rpx;
					margin-top: 4rpx;
					flex-shrink: 0;
				}

				.tip-text {
					font-size: 28rpx;
					color: #606266;
					line-height: 1.6;
					flex: 1;
				}
			}
		}
	}

	.subscription-section {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

		.section-header {
			display: flex;
			align-items: center;
			margin-bottom: 32rpx;

			.header-icon {
				width: 48rpx;
				height: 48rpx;
				background: linear-gradient(135deg, #ff6444 0%, #ff8e53 100%);
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-right: 16rpx;

				.cuIcon-settings {
					font-size: 24rpx;
					color: #FFFFFF;
				}
			}

			.header-title {
				font-size: 32rpx;
				color: #2C2622;
				font-weight: 600;
			}
		}

		.subscription-list {
			.subscription-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 24rpx 0;
				border-bottom: 1rpx solid #f5f5f5;

				&:last-child {
					border-bottom: none;
				}

				.item-content {
					display: flex;
					align-items: center;
					flex: 1;

					.item-icon {
						width: 48rpx;
						height: 48rpx;
						background: #f8f9fa;
						border-radius: 12rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 16rpx;

						text {
							font-size: 24rpx;
							color: #ff6444;
						}
					}

					.item-info {
						flex: 1;

						.item-title {
							font-size: 28rpx;
							color: #2C2622;
							font-weight: 500;
							margin-bottom: 8rpx;
							display: block;
						}

						.item-desc {
							font-size: 24rpx;
							color: #8F97A2;
							line-height: 1.4;
						}
					}
				}

				.item-action {
					.subscribe-btn {
						padding: 12rpx 24rpx;
						border-radius: 20rpx;
						font-size: 24rpx;
						font-weight: 500;
						border: none;
						transition: all 0.2s;

						&:not(.subscribed) {
							background: linear-gradient(135deg, #ff6444 0%, #ff8e53 100%);
							color: #FFFFFF;

							&:active {
								transform: scale(0.95);
							}
						}

						&.subscribed {
							background: #f0f0f0;
							color: #8F97A2;
						}

						.btn-text {
							font-size: 24rpx;
						}
					}
				}
			}
		}
	}

	.all-subscription-section {
		.all-subscribe-btn {
			width: 100%;
			height: 88rpx;
			background: linear-gradient(135deg, #ff6444 0%, #ff8e53 100%);
			color: #FFFFFF;
			border-radius: 20rpx;
			font-size: 32rpx;
			font-weight: 600;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			box-shadow: 0 8rpx 32rpx rgba(255, 100, 68, 0.3);

			&:active {
				transform: scale(0.98);
			}

			.btn-icon {
				font-size: 28rpx;
				margin-right: 12rpx;
			}

			.btn-text {
				font-size: 32rpx;
			}
		}
	}
</style>